package en.kaist.cs408.acav;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import en.kaist.cs408.R;
import en.kaist.cs408.acav.CreateClass.NetworkHandler;

public class CheckVoice extends Activity {
	
	private Button buttonRefresh;
	private List<WifiItem> listeWifiItem;
	private WifiAdapter wifiAdapter;
	private WifiManager wifiManager;
	private WifiBroadcastReceiver broadcastReceiver;
	
	private ImageView micImg;
	private Button buttonSendInfo;
	
    private Verifier checkVoiceVerifier;
    private String hotspotAddress;
    private int networkStateIndicator;
    private boolean isWifiMatched;
    private boolean isRecording;
    private boolean isRecordComplete;
    private VoiceRecorder vr;
    
    private EditText cidEditText;
    private String courseID;
    private EditText sidEditText;
    private String studentID;

    
    private String voiceFileName;
    
	public void onCreate(Bundle savedInstanceState) {
     
		super.onCreate(savedInstanceState);
    
		checkVoiceVerifier = new Verifier();
		
		
		setContentView(R.layout.checkvoice);
		
		
		buttonRefresh = (Button) findViewById(R.id.buttonRefresh);
		micImg = (ImageView) findViewById(R.id.micImgView);
		buttonSendInfo = (Button) findViewById(R.id.buttonSendInfo);
		
		/* Initialization */
		isWifiMatched = false;
		isRecording = false;
		isRecordComplete = false;
		
		hotspotAddress = null;
		cidEditText = null;
		courseID = null;
		sidEditText = null;
		studentID = null;
		
		vr = new VoiceRecorder();
		
		//Android Wifi service is required
		wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
		
		// Wifi AP list management
		listeWifiItem = new ArrayList<WifiItem>();
		wifiAdapter = new WifiAdapter(this, listeWifiItem);
		

		//Receiver broadcast creation
		broadcastReceiver = new WifiBroadcastReceiver();

		// Receiver is linked to scan result
		registerReceiver(broadcastReceiver, new IntentFilter(
				WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
		if(wifiManager != null)
		{
			wifiManager.startScan();
		}
		
		buttonRefresh.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				cidEditText = (EditText)findViewById(R.id.checkvoice_courseID);
				courseID = cidEditText.getText().toString();
				
				if (!checkVoiceVerifier.verifyCourseID(courseID)){
					AlertDialog.Builder ad = new AlertDialog.Builder(CheckVoice.this);
					ad.setTitle("Alert");
					ad.setPositiveButton("Yes", null);
					ad.setMessage("Please enter your course ID");
					ad.show();
				}
				else {
					// Send courseID information to server
					// and receive the WIFI hotspot's mac address and the keyword
					if (!wifiManager.isWifiEnabled())
						wifiManager.setWifiEnabled(true);
					
					while(!wifiManager.isWifiEnabled()) {/* waiting */ }
					
					wifiManager.startScan();
					
					NetworkHandler handler = new NetworkHandler(){
						public void handleMessage(Message msg){
							switch (msg.what){
							case 0:
								//Toast.makeText(CheckVoice.this, "Server complete", Toast.LENGTH_LONG).show();
								String tmpHotspot = (String)msg.obj;
								hotspotAddress = tmpHotspot.toLowerCase();
								networkStateIndicator = 0;
								
								for(WifiItem myWifiItem : listeWifiItem){
									if(hotspotAddress.equals(myWifiItem.getAdresseMac()) ){
										TextView textWifiCheck = (TextView) findViewById(R.id.wifiCheckState);
										textWifiCheck.setText("Wifi Checking is OK");
										textWifiCheck.setTextColor(Color.GREEN);
										isWifiMatched = true;
										break;
									}
								}
								break;
							case -1:
								networkStateIndicator = -1;
								Toast.makeText(CheckVoice.this, "No such Course ID", Toast.LENGTH_LONG).show();
								break;
							case -2:
								networkStateIndicator = -2;
								Toast.makeText(CheckVoice.this, "Checking ends up", Toast.LENGTH_LONG).show();
								break;
							default:
								networkStateIndicator = msg.what;
								Toast.makeText(CheckVoice.this, "Exception Occurred", Toast.LENGTH_LONG).show();
								break;	
							}
						}
					};
					
					NetworkThread nt = new NetworkThread(1000, courseID, null, null, null, null,null,null, false, handler);
					nt.start();
					
				
				
				}
			}
		});

		micImg.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ImageView micImgView = (ImageView)findViewById(R.id.micImgView);
				
				if (isRecording == false){
					/* Check and extract the courseID and studentID */
					
					if (isWifiMatched==false){
						AlertDialog.Builder ad = new AlertDialog.Builder(CheckVoice.this);
						ad.setTitle("Alert");
						ad.setPositiveButton("Yes", null);
						ad.setMessage("Please touch the [Check Wifi] button");
						ad.show();
					}
					else {
						/* Recording process */
						isRecording = true;
						micImgView.setImageResource(R.drawable.mic_recording);
						vr.startRecording();
					}
				} else {
					isRecording = false;
					micImgView.setImageResource(R.drawable.mic);
					vr.stopRecording();
					
					/* post-process of recorded file*/
					/* or post-process can be inserted in VoiceRecorder.java */
					isRecordComplete = true;
				}
			}});
		
		buttonSendInfo.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				AlertDialog.Builder ad = new AlertDialog.Builder(CheckVoice.this);
				ad.setTitle("Alert");
				ad.setPositiveButton("Yes", null);
				
				
				/* server/client communication */
				/* info to send - courseID, studentID, recorded voice file */
				
				if (isRecordComplete == false){
					ad.setMessage("Please touch the MIC and record your voice.");
					ad.show();
				} else {
					cidEditText = (EditText)findViewById(R.id.checkvoice_courseID);
					courseID = cidEditText.getText().toString();
					
					sidEditText = (EditText)findViewById(R.id.checkvoice_studentID);
					studentID = sidEditText.getText().toString();
					voiceFileName = vr.getFileName();
					
					Log.d("Chwang", voiceFileName);
					
					if (studentID.compareTo("")==0){
						ad.setMessage("Please type your student ID");
						ad.show();
					}
					else {
						// Sending process
						
						// Receive the result (state protocol should be fixed)
						// show result to client
						// NetworkHandler should be re-written
						
						
						NetworkHandler handler = new NetworkHandler(){
							public void handleMessage(Message msg){
								AlertDialog.Builder ad = new AlertDialog.Builder(CheckVoice.this);
								ad.setTitle("Alert");
								ad.setPositiveButton("Yes", null);
								
								switch (msg.what){
								case 0:
									Toast.makeText(CheckVoice.this,  "Currently successful", Toast.LENGTH_LONG).show();
									break;
								case -1:
									//Toast.makeText(CheckVoice.this, "No such Course ID", Toast.LENGTH_LONG).show();
									ad.setMessage("No such Course ID exists. Please Check typo.");
									ad.show();
									break;
								case -2:
									Toast.makeText(CheckVoice.this, "No such Student ID in the course", Toast.LENGTH_LONG).show();
									
									AlertDialog.Builder ad2 = new AlertDialog.Builder(CheckVoice.this);
									ad2.setTitle("Alert");
									ad2.setMessage("No such Student ID in the course. Would you like to register?"
											+ "\nCourse ID: "+courseID+"\nStudent ID: "+studentID);
									
									
									ad2.setNegativeButton("No", null);
									
									ad2.setPositiveButton("Yes",
											new DialogInterface.OnClickListener() {
												@Override
												public void onClick(DialogInterface dialog, int which) {
													NetworkHandler handler = new NetworkHandler(){
														public void handleMessage(Message msg){
															switch(msg.what){
															case 0:
																//Toast.makeText(CheckVoice.this, "Registration Complete", Toast.LENGTH_LONG).show();
																AlertDialog.Builder ad = new AlertDialog.Builder(CheckVoice.this);
																ad.setTitle("Congratulation");
																ad.setMessage("Registration Complete!");
																ad.setPositiveButton("Home", new DialogInterface.OnClickListener(){
																	@Override
																	public void onClick(DialogInterface dialog, int which) {
																		Intent homeActivity = new Intent(CheckVoice.this, Home.class);
																		startActivity(homeActivity);
																		finish();
																	}
																});
																ad.show();
																break;
															default:
																Toast.makeText(CheckVoice.this, "Server got problem..", Toast.LENGTH_LONG).show();
																break;
															}
														}};
													
													NetworkThread nt = new NetworkThread(1300, courseID, studentID, null, null, null,null,null, false, handler);
													nt.start();
												}

									});

									ad2.show();
									
									break;
								default:
									//Toast.makeText(CheckVoice.this, "Exception Occurred", Toast.LENGTH_LONG).show();
									ad.setMessage("Exception Occurred. Please try it later.");
									ad.show();
									break;	
								}
							}
						};
						
						NetworkThread nt = new NetworkThread(1100, courseID, studentID, null, null, voiceFileName,null,null, false, handler);
						nt.start();
						
						
						NetworkHandler wavHandler = new NetworkHandler(){
							public void handleMessage(Message msg){
								AlertDialog.Builder ad = new AlertDialog.Builder(CheckVoice.this);
																
								switch(msg.what){
								case 0:
									// SuckSex
									ad.setTitle("Welcome to Class!");
									ad.setMessage("You succeed to attend class");
									
									ad.setPositiveButton("Home", new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											Intent homeActivity = new Intent(CheckVoice.this, Home.class);
											startActivity(homeActivity);
											finish();
										}
									});
									ad.show();
									//Toast.makeText(CheckVoice.this, "Checking Success!!", Toast.LENGTH_LONG).show();
									break;
								case -10:
									// Fail
									ad.setTitle("Alert");
									ad.setMessage("Who are YOU???????");
									
									ad.setPositiveButton("Try Again", null);
									//Toast.makeText(CheckVoice.this, "Checking Failed..", Toast.LENGTH_LONG).show();
									break;
								case -100:
									// SQLException
									Toast.makeText(CheckVoice.this, "SQLException occurred", Toast.LENGTH_LONG).show();
									break;
								case -1000:
									// Registration
									//Toast.makeText(CheckVoice.this, "Registration", Toast.LENGTH_LONG).show();
									break;
								default:
									// No course ID or No student ID in the course
									Toast.makeText(CheckVoice.this, "No course", Toast.LENGTH_LONG).show();
									break;
								}
							}
						};
						
						WavNetworkThread wnt = new WavNetworkThread("cs408.kaist.ac.kr", 3080, courseID, studentID, voiceFileName, wavHandler);
						wnt.start();
					}
				}	
			}});
		
	}
	
	// When pause is set, receiver is stopped
		@Override
		protected void onPause() {
			unregisterReceiver(broadcastReceiver);
			super.onPause();
		}

		// When the application starts again, receiver is reloaded
		@Override
		protected void onResume() {
			registerReceiver(broadcastReceiver, new IntentFilter(
					WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
			super.onResume();
		}

		public WifiManager getCurrentWifiManager() {
			return wifiManager;
		}
		
		public WifiAdapter getWifiAdapter() {
			return wifiAdapter;
		}
		
		public List<WifiItem> getListeWifiItem() {
			return listeWifiItem;
		}
	
}